package estore.src.estore.service;
import estore.src.estore.model.Product;
import java.util.*;
import java.io.*;
import java.util.Properties;

/**
 * 商品服务类，负责商品的管理操作
 */
public class ProductService {
    private Map<String, Product> products = new HashMap<>();
    private String dataFilePath;

    public ProductService() {
        loadConfig(); // 先加载配置
        loadData();   // 再加载数据
    }


    private void loadConfig() {
        Properties props = new Properties();
        File configFile = new File("config.properties");

        if (!configFile.exists()) {
            // 如果配置文件不存在，使用默认值并创建配置文件
            dataFilePath = "products.dat";
            saveDefaultConfig();
            System.out.println("配置文件不存在，已创建默认配置");
            return;
        }

        try (InputStreamReader reader = new InputStreamReader(
                new FileInputStream("config.properties"), "UTF-8")) {
            props.load(reader);
            dataFilePath = props.getProperty("data.file.path", "products.dat");
            System.out.println("配置文件加载成功，数据文件路径: " + dataFilePath);
        } catch (IOException e) {
            System.err.println("加载配置文件失败: " + e.getMessage());
            dataFilePath = "products.dat"; // 使用默认值
        }
    }


    private void saveDefaultConfig() {
        Properties props = new Properties();
        props.setProperty("data.file.path", "products.dat");

        try (OutputStreamWriter writer = new OutputStreamWriter(
                new FileOutputStream("config.properties"), "UTF-8")) {
            props.store(writer, "电子商店系统配置");
        } catch (IOException e) {
            System.err.println("保存默认配置失败: " + e.getMessage());
        }
    }


    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(dataFilePath))) {
            oos.writeObject(products);
            System.out.println("数据已保存到: " + dataFilePath);
        } catch (IOException e) {
            System.err.println("保存数据失败: " + e.getMessage());
        }
    }


    @SuppressWarnings("unchecked")
    public void loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) {
            System.out.println("数据文件不存在，将创建新文件");
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(dataFilePath))) {
            products = (Map<String, Product>) ois.readObject();
            System.out.println("数据已从 " + dataFilePath + " 加载，共 " + products.size() + " 个商品");
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("加载数据失败: " + e.getMessage());
            // 如果加载失败，保持空的products映射
            products = new HashMap<>();
        }
    }


    public boolean addProduct(Product product) {
        if (products.containsKey(product.getId())) {
            return false; // 商品ID已存在
        }
        products.put(product.getId(), product);
        return true;
    }


    public boolean removeProduct(String productId) {
        return products.remove(productId) != null;
    }

    public boolean updateProduct(Product product) {
        if (!products.containsKey(product.getId())) {
            return false; // 商品不存在
        }
        products.put(product.getId(), product);
        return true;
    }

    /**
     * 根据ID查找商品
     */
    public Product findProductById(String productId) {
        return products.get(productId);
    }

    /**
     * 获取所有商品列表（按ID排序）
     */
    public List<Product> getAllProducts() {
        List<Product> productList = new ArrayList<>(products.values());
        Collections.sort(productList);
        return productList;
    }

    /**
     * 根据名称搜索商品
     */
    public List<Product> searchProductsByName(String name) {
        List<Product> result = new ArrayList<>();
        for (Product product : products.values()) {
            if (product.getName().toLowerCase().contains(name.toLowerCase())) {
                result.add(product);
            }
        }
        Collections.sort(result);
        return result;
    }

    /**
     * 更新商品库存
     */
    public boolean updateStock(String productId, int newStock) {
        Product product = products.get(productId);
        if (product == null) {
            return false;
        }
        try {
            product.setStock(newStock);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * 获取商品数量
     */
    public int getProductCount() {
        return products.size();
    }
}